<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        echo "hello world";
    }

    public function swoole_client()
    {
        $client = new \swoole_client(SWOOLE_SOCK_TCP);
        //连接到服务器
        if (!$client->connect('127.0.0.1', 9501, 0.5))
        {
            echo 'connect success';
        }

        $data			=	array();
        $data['game']	=	'worldcup';
        $data['action'] =	'Push';
        $data['test']   =   '';
        $data['call_back'] =   'http://test.beikg.cn/home/index/api_accept';

        $msg 			=	serialize($data);

        //向服务器发送数据
        if (!$client->send($msg))
        {
            echo ' send failed';
        }
        else
        {
            echo ' send success';
        }

        //关闭连接
        $client->close();
    }

    public function set_push()
    {
        $member_data 	=	M('newsong_template_send')->select();

        if(! empty($member_data))
        {

            $redis = new \Redis();
            $redis->connect('127.0.0.1',6379);
            foreach($member_data as $key=> $val)
            {
                $redis->rPush('demo_push',json_encode($val));
                $key++;
                echo '插入一条数据'.$key;
            }

        }

        $num     =   memory_get_usage();

        echo '消耗内存：'.$this->getFilesize($num);
    }

    public function api_accept()
    {
        if(! empty($_POST))
        {
            /*
            $redis = new \Redis();
            $redis->connect('127.0.0.1',6379);
            $redis->rPush('demo2_push',json_encode($_POST));
            */
            $insert_data['log']    =    json_encode($_POST);
            M('yao_log')->add($insert_data);
            //echo '接受处理666';

            //print_r($_POST);
        }

        $insert_data['log']    =    999;
        M('yao_log')->add($insert_data);
    }

    public function push_zuji_status()
    {
        $redis = new \Redis();

        $redis->connect('127.0.0.1',6379);

        $worldcup_member        =   $redis->get('worldcup_member');

        $worldcup_member        =   json_decode($worldcup_member,true);

        echo '数据：'.count($worldcup_member);

        echo "</br>";

        $loop 	=	true;

        while ($loop)
        {
            $game = 'pushed_message_worldcup';

            $value = $redis->lpop($game);
            if ($value)
            {
                echo $value.'已经推送';
            }
            else
            {
                $loop   =   false;
            }
        }
    }

    public function push_zuji()
    {
        $template_data 	=	M('worldcup_template_send')->select();
        if(! empty($template_data))
        {
            $redis = new \Redis();

            $redis->connect('127.0.0.1',6379);

            $appid		=	'wxb26efa19cb837835';

            $secret		=	'86cd81876b2c203de94f6b17e6f144e9';

            $access_token = $this->gettoken($appid,$secret);

            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";

            $tem = "JYhnftZ3mQ1OBdQ9a2EjTYAQomZt-gnVOJbLRWj4WYM";

            $fdata = array(
                'keyword1'=>array(
                    'value'=>'2018俄罗斯世界杯',
                    'color'=>'#173177',
                ),
                'keyword2'=>array(
                    'value'=>'6月14日--7月15日',
                    'color'=>'#ff0000',
                ),
                'keyword3'=>array(
                    'value'=>'22：00 澳大利亚 vs 秘鲁',
                    'color'=>'#173177',
                ),
            );

            $worldcup_member        =   $redis->get('worldcup_member');

            $worldcup_member        =   json_decode($worldcup_member,true);

            $worldcup_member        =   array();

            foreach($template_data as $key=> $value)
            {
                if (! in_array($value['touser'], $worldcup_member) && $value['form_id'] !=  'the formId is a mock one')
                {
                    $data = array(
                        'touser'=>$value['touser'],
                        'template_id'=>$tem,
                        'page'=>'pages/index/index',
                        'form_id'=>$value['form_id'],
                        'data'=>$fdata,
                        'emphasis_keyword'=>'keyword2.DATA'
                    );

                    $post_data 			=	array();
                    $post_data['data']	=	$data;
                    $post_data['url']	=	$url;
                    $post_data['id']	=	$value['wxopen_template_send_id'];


                    $redis->rPush('push_message_worldcup',json_encode($post_data));

                    $worldcup_member[]  =   $value['touser'];

                    $member_data    =   json_encode($worldcup_member);
                    $redis->set('worldcup_member', $member_data);

                    $key++;

                    echo '插入一条数据'.$key;

                }
            }

        }

    }

    public function gettoken($appid,$secret){

        $where['appid'] 	= $appid;
        $where['secret'] 	= $secret;
        $token =  M('access_token')->field('access_token,expires_in,createtime')->where($where)->find();
        $access_token = $token['access_token'];
        if (time()-$token['access_token']>=$token['expires_in']){
            $access_token = $this->updatetoken($appid,$secret);
        }
        return $access_token;
    }

    public function updatetoken($appid,$secret){

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $res = $this->curlget($url);

        $where['appid'] = $appid;
        $where['secret'] = $secret;
        $token =  M('access_token')->field('access_token')->where($where)->find();

        $data = array(
            'access_token'=>$res['access_token'],
            'expires_in'=>$res['expires_in'],
            'createtime'=>time(),
            'appid'=>$appid,
            'secret'=>$secret,
        );
        if ($token){
            M('access_token')->where($where)->save($data);
        }else{
            if ($res['access_token']){
                M('access_token')->data($data)->add();
            }
        }

        return $res['access_token'];
    }

    public function curlget($url){
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        $response = curl_exec($ch);
        curl_close( $ch );
        $rest = json_decode($response,true);
        return $rest;
    }

    private function getFilesize($num){
        $p = 0;
        $format='bytes';
        if($num>0 && $num<1024){
            $p = 0;
            return number_format($num).' '.$format;
        }
        if($num>=1024 && $num<pow(1024, 2)){
            $p = 1;
            $format = 'KB';
        }
        if ($num>=pow(1024, 2) && $num<pow(1024, 3)) {
            $p = 2;
            $format = 'MB';
        }
        if ($num>=pow(1024, 3) && $num<pow(1024, 4)) {
            $p = 3;
            $format = 'GB';
        }
        if ($num>=pow(1024, 4) && $num<pow(1024, 5)) {
            $p = 3;
            $format = 'TB';
        }
        $num /= pow(1024, $p);
        return number_format($num, 3).' '.$format;
    }

}